import json

from loguru import logger

def parse_data(response):
    try:
        result_json = response.json()
        logger.info(f"Response: {json.dumps(result_json, ensure_ascii=False)}")
        result_data = result_json['data']
        basic_data = result_data['basicData']

        return {
        # "id": 172456136,
        # "company_id": "aaf60e827737aab67641f99b5d8d1a29",
        # "province_short": "GD",
        "industry": basic_data["industry"],
        "prevEntName": basic_data["prevEntName"],
        "company_name": basic_data["entName"],
        "company_code": "440126000788807",
        "credit_no": basic_data["unifiedCode"],
        "org_code": basic_data["regNo"][7:-1],
        "tax_code": basic_data["taxNo"],
        "establish_date": basic_data["startDate"],
        "legal_person": basic_data["legalPerson"],
        "legal_person_caption": basic_data["personTitle"],
        "company_status": basic_data["openStatus"],  # "在营（开业）企业",
        "company_type": basic_data["entType"],  # "有限责任公司(法人独资)",
        "authority": basic_data["authority"],  # "广州市番禺区工商行政管理局",
        "issue_date": basic_data["annualDate"],  # "2016-12-26",
        "operation_startdate": str.split(basic_data["openTime"], '至')[0],
        "operation_enddate": str.split(basic_data["openTime"], '至')[1] if len(str.split(basic_data["openTime"], '至')) > 1 else str.split(basic_data["openTime"], '至')[0],
        "capital": basic_data["regCapital"],  # ,"100.000000万人民币",
        "company_address": basic_data["regAddr"],  # "广州市番禺区小谷围街大学城中六路1号广州大学城信息枢纽楼三楼302-B",
        "business_scope": basic_data["scope"],
        # "软件开发;信息系统集成服务;信息技术咨询服务;数据处理和存储服务;集成电路设计;数据交易服务;数据处理和存储产品设计;商品信息咨询服务;信息电子技术服务;科技信息咨询服务;企业管理咨询服务;软件服务;市场营销策划服务;策划创意服务;群众参与的文艺类演出、比赛等公益性文化活动的策划;广告业;市场调研服务;",
        # "cancel_date": null,
        # "cancel_reason": null,
        # "revoke_date": null,
        # "revoke_reason": null,
        # "create_time": "2018-05-20 17:16:33",
        # "update_time": "2023-01-21 08:45:51",
        # "legal_person_type": 0,
        "real_capital": basic_data["paidinCapital"],  # "100万人民币",
        # "en_name": null,
        "company_branch": company_branch(result_data),
        "company_change": company_change(result_data),
        "company_employee": company_employee(result_data),
        "company_history_name": basic_data["prevEntName"],
        #     [
        #     {
        #         "id": 12485848,
        #         "company_id": "5daf2ca3bddac544dd2bc18263f800d4",
        #         "history_name": "广州市越秀区智能制作公司",
        #         "change_date": null,
        #         "start_date": null,
        #         "end_date": null,
        #         "use_flag": 0,
        #         "create_time": "2021-05-26 08:27:19",
        #         "update_time": "2021-05-26 08:27:19"
        #     }
        # ],
        "company_industry": basic_data["industry"],
        #
        #     [
        #     {
        #         "id": 53243866,
        #         "company_id": "aaf60e827737aab67641f99b5d8d1a29",
        #         "industry": "软件开发",
        #         "industry_l1_code": "I",
        #         "industry_l1_name": "信息传输、软件和信息技术服务业",
        #         "industry_l2_code": "65",
        #         "industry_l2_name": "软件和信息技术服务业",
        #         "industry_l3_code": "651",
        #         "industry_l3_name": "软件开发",
        #         "industry_l4_code": null,
        #         "industry_l4_name": null,
        #         "use_flag": 0,
        #         "create_time": "2018-05-20 17:16:33",
        #         "update_time": "2022-03-23 14:32:06"
        #     }
        # ],
        # "company_partner":
        # [
        #     {
        #         "id": 23086351,
        #         "company_id": "aaf60e827737aab67641f99b5d8d1a29",
        #         "stock_name": "广州达咖信息科技有限公司",
        #         "company_name": "广州娱狗科技有限公司",
        #         "stock_type": "法人股东",
        #         "is_personal": 0,
        #         "stock_name_id": "2386d52e3b11b1d96c15546a6e71941e",
        #         "identify_type": "企业法人营业执照（公司）",
        #         "identify_no": "91440104MA59B68798",
        #         "stock_capital": "100万人民币",
        #         "stock_realcapital": null,
        #         "stock_proportion": 1,
        #         "invest_type": null,
        #         "invest_realtype": null,
        #         "use_flag": 0,
        #         "is_history": 0,
        #         "create_time": "2020-03-15 13:17:54",
        #         "update_time": "2023-06-14 13:18:32"
        #     }
        # ],
        "company_partner_pay":company_pay(result_data),
        # "company_partner_realpay": [
        #     {
        #         "id": 22888757,
        #         "company_id": "5daf2ca3bddac544dd2bc18263f800d4",
        #         "stock_name": "张正义",
        #         "realpay_record": "5beaa49b508962d0faec76fcc38df28b",
        #         "stock_realcapital": "2500.0万元",
        #         "invest_realtype": "货币",
        #         "stock_realdate": "2009-12-18",
        #         "use_flag": 0,
        #         "is_history": 0,
        #         "create_time": "2020-09-17 11:56:35",
        #         "update_time": "2022-05-29 18:44:04"
        #     }
        # ],
        # "company_profile": [
        #     {
        #         "id": 227048133,
        #         "company_name": "广州娱狗科技有限公司",
        #         "company_abbreviation": "娱狗科技",
        #         "company_id": "aaf60e827737aab67641f99b5d8d1a29",
        #         "company_profile": "广州娱狗科技有限公司，2016-12-26日成立，经营范围包括软件开发;信息系统集成服务;信息技术咨询服务;数据处理和存储服务;集成电路设计;数据交易服务;数据处理和存储产品设计;商品信息咨询服务;信息电子技术服务;科技信息咨询服务;企业管理咨询服务;软件服务;市场营销策划服务;策划创意服务;群众参与的文艺类演出、比赛等公益性文化活动的策划;广告业;市场调研服务;",
        #         "profile_flag": 0,
        #         "create_time": "2022-06-21 14:00:37",
        #         "update_time": "2022-06-21 14:00:37",
        #         "use_flag": 0
        #     }
        # ]
    }
    except Exception as e:
        logger.info("详情抓取失败, 准备换ip")
        return None


def company_branch(result_data):
    result_arr = []
    branch_data = result_data['branchsData']
    for data in branch_data["list"]:
        result_arr.append({
                # "id": 9713254,
                # "company_id": "5daf2ca3bddac544dd2bc18263f800d4",
                "branch_name": data["entName"],
                # "branch_company_id": "cca3fdc2b1d6e18ff2cf6d512713c45d",
                # "branch_code": null,
                # "branch_credit_no": null,
                "establish_date": data["startDate"],
                "company_status": data["openStatus"],
                # "n_company_status": null,
                # "authority": null,
                # "cancel_date": "2002-04-29",
                # "revoke_date": null,
                # "use_flag": 10,
                # "create_time": "2022-03-16 03:02:07",
                # "update_time": "2022-12-19 18:33:43"
           })

    return result_arr


def company_change(result_data):
    result_arr = []
    change_data = result_data['changeRecordData']["list"]
    if len(change_data):
        return  result_arr
    for data in change_data:
        result_arr.append({

            # "change_type": null,
            "change_field": data["fieldName"],
            "content_before": data["oldValue"],
            "content_after": data["newValue"],
            "change_date": data["date"]
            # "use_flag": 0,
            # "create_time": "2020-03-20 11:57:58",
            # "update_time": "2020-03-20 11:57:58"
        })

    return result_arr

def company_employee(result_data):
    result_arr = []
    dir_data = result_data['directorsData']["list"]
    if len(dir_data):
        return result_arr
    for data in dir_data:
        result_arr.append(  {
                # "id": 19725801,
                # "company_id": "aaf60e827737aab67641f99b5d8d1a29",
                "employee_name": data["name"],
                "position": data["positionTitle"],
                "is_history": 0,
                "use_flag": 0,
                # "create_time": "2018-05-20 17:16:33",
                # "update_time": "2020-04-30 16:40:00",
                "education": data["educationLevel"],
                "age": data["personAge"],
                # "sex": null,
                # "person_id": "dcdb5ff50a775118662389dd20b49ad5",
                # "employee_name_type": 0
            },)

    return result_arr

def company_pay(result_data):
    result_arr = []
    invest_data = result_data['investRecordData']["list"]
    if len(invest_data) == 0:
        return invest_data
    for data in invest_data:
        result_arr.append( {
                # "id": 70828393,
                # "company_id": "5daf2ca3bddac544dd2bc18263f800d4",
                "stock_name": data["logoWord"],
                # "pay_record": "5beaa49b508962d0faec76fcc38df28b",
                "stock_capital":data["regCapital"],
                # "invest_type": "货币",
                # "stock_date": "2009-12-18",
                # "use_flag": 0,
                # "is_history": 0,
                # "create_time": "2020-10-04 09:59:46",
                # "update_time": "2022-05-29 18:44:04"
            })

    return result_arr